package com.zzl.study.demo.tool;

import cn.hutool.core.util.RuntimeUtil;
import com.zzl.study.demo.domain.MavenDependency;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * Maven命令工具服务
 *
 * @author: zhangzl
 * @date: 2025/10/17 15:14
 * @version: 1.0
 */
public class MavenService {

    /**
     * Maven安装目录
     */
    @Value("${maven.home}")
    private String mavenHome;

    /**
     * 获取指定Maven项目中冲突的依赖项
     *
     * @param targetPath 目标路径
     * @return 冲突的依赖项
     */
    @Tool(name = "get_conflicting_dependencies", description = "获取指定Maven项目中冲突的依赖项")
    public String getConflictingDependencies(@ToolParam(description = "指定Maven项目路径") String targetPath) {
        File project = new File(targetPath);
        if (!project.exists()) {
            return "项目路径不存在!";
        }
        if (!project.isDirectory()) {
            return "项目路径不是目录!";
        }
        Optional<File> pomFile = Arrays.stream(Objects.requireNonNull(project.listFiles())).filter(file -> file.isFile() && "pom.xml".equals(file.getName())).findFirst();
        if (pomFile.isEmpty()) {
            return "项目路径下不存在pom.xml文件!";
        }
        String mavenCommand = getCommandPrefix() + " dependency:tree -Dverbose -f " + pomFile.get().getAbsolutePath();
        List<String> analysisResult = RuntimeUtil.execForLines(mavenCommand);
        List<MavenDependency> conflictingDependencies = analysisResult.stream().filter(line -> line.contains("omitted for conflict with")).map(this::parseDependency).toList();
        StringBuilder sb = new StringBuilder();
        sb.append("项目 ").append(project.getName()).append(" 有冲突的依赖项如下： \n");
        for (MavenDependency dependency : conflictingDependencies) {
            sb.append("- ").append(dependency.formatString()).append("\n");
        }
        return sb.toString();
    }

    /**
     * 解析依赖项
     *
     * @param line 依赖项行
     * @return 解析后的依赖项
     */
    private MavenDependency parseDependency(String line) {
        if (line.contains("(")) {
            line = line.substring(line.indexOf("(") + 1, line.length() - 1);
        }
        String[] split = line.split(" ");
        String dependencyInfo = split[0];
        String[] dependencyInfoSplit = dependencyInfo.split(":");
        MavenDependency dependency = new MavenDependency();
        dependency.setGroupId(dependencyInfoSplit[0]);
        dependency.setArtifactId(dependencyInfoSplit[1]);
        dependency.setType(dependencyInfoSplit[2]);
        dependency.setVersion(dependencyInfoSplit[3]);
        dependency.setScope(dependencyInfoSplit[4]);
        if (dependencyInfoSplit.length > 5) {
            dependency.setClassifier(split[5]);
        }
        return dependency;
    }

    /**
     * 获取Maven命令前缀
     *
     * @return Maven命令前缀
     */
    private String getCommandPrefix() {
        String mvnExecutable = System.getProperty("os.name").toLowerCase().contains("win") ? "mvn.cmd" : "mvn";
        return mavenHome + File.separator + "bin" + File.separator + mvnExecutable;
    }

}
